package co.za.itweb.itwebpro;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.WindowManager;

public class Overlay extends FragmentActivity {

	JSONArray sectionsOrder;
	String URL;
	protected static final String PREFS_NAME = "QUERYFIELDS";
	private MainAsyncTask MAT;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_overlay);
		MAT = new MainAsyncTask(this);
		MAT.execute();
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	public class MainAsyncTask extends AsyncTask<Void, Integer, Void> {
		InputStream is;
		String result;
		Overlay myactivity;

		public MainAsyncTask(FragmentActivity activity) {
			this.myactivity = (Overlay) activity;
		}

		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... arg0) {

			try {

				if(parseConfig()){
					System.out.println("PARSED");
				MainActivity.refreshed = true;
				}else{
					Intent returnIntent = new Intent();	
					setResult(0, returnIntent);
					finish();
				}

			} catch (FileNotFoundException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			if (isCancelled()) {
				Intent returnIntent = new Intent();
				setResult(0, returnIntent);
				finish();
			}

			return null;
		}

		
		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		@Override
		protected void onPostExecute(Void result) {
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(1, returnIntent);
			finish();
		}

		public boolean parseConfig() throws FileNotFoundException, IOException {
			
			URL = "http://itweb.mobi/__itweb_pro/feed/iosv3/_load.php?parse_type=intro";
		
			try {

				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(URL);

				JSONObject obj = new JSONObject();
				obj.put("conf", "conf");
				httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

				httppost.setHeader("Accept", "application/json");
				httppost.setHeader("Content-type", "application/json");

				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

			} catch (Exception e) {
				Log.e("log_tag", "Error in http connection " + e.toString());
				return false;
			}

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");

				}

				is.close();
				result = sb.toString();

			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
				return false;
			}

			// try parse the string to a JSON object
			try {
				MainActivity.jsonIntroObject=null;
				MainActivity.jsonIntroObject = new JSONObject(result);
				sectionsOrder = MainActivity.jsonIntroObject
						.getJSONArray("sections_order");
				MainActivity.sectionsName = MainActivity.jsonIntroObject
						.getJSONObject("sections_available");

				MainActivity.sectionsOrdering = JsonUtil2
						.getStringListFromJsonArray(sectionsOrder);

				return true;

			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());

			}

			return false;

		}
	}

	@SuppressLint("WorldReadableFiles")
	public String checkDisabledFields() {
		try {
			SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
					MODE_WORLD_READABLE);
			String disabledFields = myPrefs.getString(
					"co.za.itweb.itwebpro.settings", "dis");

			if (disabledFields != null && disabledFields.length() > 2) {
				JSONArray dat = new JSONArray(disabledFields);

				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.get(t).toString();

						return "true";
					} catch (JSONException e) {
						e.printStackTrace();

					}
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return null;
	}

}
